package daos

import (
	"gorm.io/gorm"
	"sanrenx.com/xyxf/app/models"
)

type CategoryDao struct {
	DB *gorm.DB
}

/**
 * @Description: 获取类型下分类列表
 * @receiver dao
 * @param mode 类型
 * @return list 分类列表
 * @return err 异常信息
 */
func (dao *CategoryDao) GetCategoriesByMode(mode string, pid int) (list []*models.Category, err error) {
	if err = dao.DB.Table("category").
		Select([]string{
			"id",
			"name",
			"icon_url",
		}).Where("mode = ?", mode).  //模式
		Where("pid = ?", pid).       //父级ID
		Where("deleted_at is NULL"). //未删除
		Order("weight ASC").         //热度倒序
		Find(&list).
		Error; err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return list, nil
}

func (dao *CategoryDao) GetCategoryIdsByPid(pIds []int) (ids []string, err error) {

	tx := dao.DB.Table("category").
		Select([]string{
			"id",
		})

	if len(pIds) == 1 {
		tx = tx.Where("pid = ?", pIds[0])
	} else {
		tx = tx.Where("pid IN ?", pIds)
	}

	//执行查询
	if err = tx.Where("deleted_at is NUll").Find(&ids).
		Error; err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return ids, nil
}
